package com.tobby.demo.jmxdemo;

import javax.management.AttributeChangeNotification;
import javax.management.MBeanNotificationInfo;
import javax.management.Notification;
import javax.management.NotificationBroadcasterSupport;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MessageEngine extends NotificationBroadcasterSupport implements
		MessageEngineMXBean {

	private static Logger log = LoggerFactory.getLogger(MessageEngine.class);

	private long sequenceNumber = 1;

	private final Message message = Echo.msg;

	public MessageEngine() {
		addNotificationListener((notification, handback) -> {
			log.info("*** Handling new notification ***");
			log.info("Message: " + notification.getMessage());
			log.info("Seq: " + notification.getSequenceNumber());
			log.info("*********************************");
		}, null, null);
	}

	@Override
	public void stop() {
		Echo.running = false;
	}

	@Override
	public boolean isPaused() {
		return Echo.pause;
	}

	@Override
	public void pause(boolean pause) {
		Notification notification = new AttributeChangeNotification(this,
				sequenceNumber++, System.currentTimeMillis(), "Pause changed", "Paused",
				"boolean", Echo.pause, pause);
		Echo.pause = pause;
		sendNotification(notification);
	}

	@Override
	public MBeanNotificationInfo[] getNotificationInfo() {
		String[] types = new String[] { AttributeChangeNotification.ATTRIBUTE_CHANGE };
		String name = AttributeChangeNotification.class.getName();
		String description = "An attribute of this bean has changed";
		MBeanNotificationInfo info = new MBeanNotificationInfo(types, name, description);
		return new MBeanNotificationInfo[] { info };
	}

	@Override
	public Message getMessage() {
		return this.message;
	}

	@Override
	public void changeMessage(Message m) {
		this.message.setBody(m.getBody());
		this.message.setTitle(m.getTitle());
		this.message.setBy(m.getBy());
	}

}